<template>
  <el-form
    v-if="getShow"
    ref="formLogin"
    :model="loginData.loginForm"
    :rules="LoginRules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row style="margin-right: -10px; margin-left: -10px">
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <template v-if="localLogin">
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item prop="username">
            <el-input
              v-model="loginData.loginForm.username"
              :placeholder="t('login.usernamePlaceholder')"
              :prefix-icon="iconAvatar"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item prop="password">
            <el-input
              v-model="loginData.loginForm.password"
              :placeholder="t('login.passwordPlaceholder')"
              :prefix-icon="iconLock"
              show-password
              type="password"
              @keyup.enter="getCode()"
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          style="padding-right: 10px; padding-left: 10px; margin-top: -20px; margin-bottom: -20px"
        >
          <el-form-item>
            <div class="flex justify-between w-1/1">
              <el-checkbox v-model="loginData.loginForm.rememberMe">
                {{ t('login.remember') }}
              </el-checkbox>
              <el-link type="primary" :underline="false" @click="localLogin = false">
                {{ t('login.uniLogin') }}
              </el-link>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item>
            <XButton
              :loading="loginLoading"
              :title="localLogin ? t('login.localLogin') : t('login.login')"
              class="w-[100%]"
              type="primary"
              @click="getCode()"
            />
          </el-form-item>
        </el-col>
      </template>
      <template v-else>
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item prop="username">
            <XButton
              :loading="loginLoading"
              :title="t('login.uniLogin')"
              class="w-[100%]"
              type="success"
              post-icon="ep:arrow-right"
              @click="goUstc()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item prop="username">
            <XButton
              :loading="loginLoading"
              :title="t('login.localLogin')"
              class="w-[100%]"
              type="primary"
              @click="localLogin = true"
            />
          </el-form-item>
        </el-col>
      </template>

      <el-col :span="24">
        <div class="confidential-warning">
          <el-icon size="20">
            <WarnTriangleFilled />
          </el-icon>
          {{ t('login.message') }}
        </div>
      </el-col>
      <el-link
        type="primary"
        :disabled="loginLoading"
        @click="setLoginState(LoginStateEnum.LOGIN_IMR)"
        >{{ t('sys.login.imrLogin') }}
      </el-link>
      <Teleport to="body">
        <Verify
          ref="verify"
          :captchaType="captchaType"
          :imgSize="{ width: '400px', height: '200px' }"
          mode="pop"
          @success="handleLogin"
        />
      </Teleport>
    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useIcon } from '@/hooks/web/useIcon'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
import * as LoginApi from '@/api/login'
import { WarnTriangleFilled } from '@element-plus/icons-vue'
import {ustcAuthorizeLogin} from "@/api/login";

defineOptions({ name: 'UstcLoginForm' })

const { t } = useI18n()
const message = useMessage()
const iconAvatar = useIcon({ icon: 'ep:avatar' }) as string
const iconLock = useIcon({ icon: 'ep:lock' }) as string
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { setLoginState, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const localLogin = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const LoginRules = {
  username: [required],
  password: [required]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})

// 获取验证码
const getCode = async () => {
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}

// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe
    }
  }
}

const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async (params) => {
  loginLoading.value = true
  try {
    const data = await validForm()
    if (!data) {
      return
    }
    const loginDataLoginForm = { ...loginData.loginForm } as any
    loginDataLoginForm.captchaVerification = params.captchaVerification
    let res
    if (localLogin.value) {
      // 走本地登录
      res = await LoginApi.ustcLocalLogin(loginDataLoginForm)
      if (!res) {
        return
      }
    } else {
      // 走统一认证
      res = await LoginApi.ustcLogin(loginDataLoginForm)
      if (!res) {
        return
      }
    }

    loading.value = ElLoading.service({
      lock: true,
      text: t('sys.login.systemLoading'),
      background: 'rgba(0, 0, 0, 0.7)'
    } as any)
    if (loginDataLoginForm.rememberMe) {
      authUtil.setLoginForm(loginDataLoginForm)
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      await push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } finally {
    loginLoading.value = false
    loading.value?.close()
  }
}

const goUstc = async () => {
  window.location.href = await LoginApi.getAuthorizeUrl(encodeURIComponent(`${window.location.protocol}//${window.location.host}/login`))
}

const handleUstcLoginCallback = async (code: string) => {
  // 走统一认证
  const res = await LoginApi.ustcAuthorizeLogin(code,`${window.location.protocol}//${window.location.host}/login`)
  authUtil.setToken(res)
  if (!redirect.value) {
    redirect.value = '/'
  }
  // 判断是否为SSO登录
  if (redirect.value.indexOf('sso') !== -1) {
    window.location.href = window.location.href.replace('/login?redirect=', '')
  } else {
    await push({ path: redirect.value || permissionStore.addRouters[0].path })
  }
}

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string

    // 从科大统一认证登录回调
    if (route?.query?.code) {
      const code = route?.query?.code as string
      handleUstcLoginCallback(code)
    }
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getLoginFormCache()
})
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.login-code {
  float: right;
  width: 100%;
  height: 38px;

  img {
    width: 100%;
    height: auto;
    max-width: 100px;
    vertical-align: middle;
    cursor: pointer;
  }
}

.confidential-warning {
  color: #ff0000;
  font-size: 18px;
  font-weight: 800;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
  margin-bottom: 10px;
}
</style>
